package ui.importandsaleman;

import o.销售单据类型;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import client.boot.BLServiceManager;
import blservice.client.ClientBLService;
import blservice.commodity.CommodityBLService;
import blservice.document.DocumentBLService;
import tool.MyButton;
import tool.MyLabel;
import vo.ClientVo;
import vo.CommodityVo;
import vo.UserVo;
import vo.Vo;
import vo.CommodityListItemVo;
import vo.SaleAndReturnDocumentVo;

import java.awt.Color;
import java.awt.Font;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

public class SaleAndReturnDocumentPanel extends JPanel{

	private static final long serialVersionUID = 1052230525756748497L;
	private SaleAndReturnDocumentVo vo;
	UserVo user;
	private JTable table;
	private JScrollPane jsp;
	private JTextField number;
	private JTextField operator;
	private boolean isNew;
	private boolean editable;
	private JComboBox<String> client;
	private List<CommodityVo> commodities;
	private 销售单据类型 type;
	private JTextField stock;
	private JTextField 备注;
	private JTextField 折让前总额;
	private JTextField 折让;
	private JTextField 代金券金额;
	private JTextField 折让后总额;
	private boolean 审批;
	private boolean 红冲;
	/**
	 * 
	 * @param user
	 * @param vo
	 *            如果是单据查询，则传入vo，如果是单据制定则传入null;
	 * @param editable
	 *            如果是新建或者红冲并复制就设置成editable
	 * @param 红冲 
	 */
	public SaleAndReturnDocumentPanel(UserVo user, SaleAndReturnDocumentVo vo, boolean editable,销售单据类型 type,boolean 审批, boolean 红冲) {
		this.红冲=红冲;
		this.审批=审批;
		this.user = user;
		this.setLayout(null);
		this.editable = editable;		
		this.type=type;		
		if(vo==null){
			this.vo=new SaleAndReturnDocumentVo();
			this.isNew=true;
		}else{
			this.isNew=false;
			this.vo=vo;
		}		
		
		this.setBackground(new Color(0, 0, 0, 0));
		JLabel label = new JLabel(this.type.name()+"制定");
		label.setForeground(Color.WHITE);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		label.setBounds(248, 10, 156, 21);
		add(label);

		JLabel label_1 = new MyLabel("\u5355\u636E\u7F16\u53F7\uFF1A");
		label_1.setBounds(47, 53, 75, 15);
		add(label_1);

		JButton add = new MyButton("Graphics/Button45-23.png");
		add.setText("+");
		add.setBounds(466, 109, 45, 23);
		if (!editable) {
			add.setVisible(false);
		}
		add.addActionListener(e -> addLine());
		add(add);

		JLabel label_4 = new MyLabel("业务员：");
		label_4.setBounds(370, 53, 54, 15);
		add(label_4);

		JButton submit = new MyButton("Graphics/Button93-23.png");
		submit.setText("\u63D0\u4EA4");
		submit.setBounds(489, 383, 93, 23);
		submit.addActionListener(e -> submit());
		if (!editable&&!审批&&!红冲) {
			submit.setVisible(false);
		}
		if(审批){
			submit.setText("通过审批");
		}
		if(红冲){
			submit.setText("红冲");
		}
		add(submit);

		JButton sub = new MyButton("Graphics/Button45-23.png");
		sub.setText("-");
		sub.setBounds(538, 109, 45, 23);
		sub.addActionListener(e -> subLine());
		if (!editable) {
			sub.setVisible(false);
		}
		add(sub);

		table = new JTable() {
			private static final long serialVersionUID = 3028897666676861555L;

			@Override
			public boolean isCellEditable(int row, int column) {
				if(editable){
					if(column==3){
						return false;
					}else{
						return true;
					}
				}else{
					return false;
				}
			}
		};
		table.setBounds(47, 128, 535, 248);
		jsp = new JScrollPane(table);
		jsp.setBounds(47, 142, 535, 204);
		jsp.setVisible(true);
		this.add(jsp);

		number = new JTextField();
		number.setEditable(false);
		number.setColumns(10);
		number.setBounds(122, 50, 105, 21);
		add(number);

		operator = new JTextField();
		operator.setEditable(false);
		operator.setColumns(10);
		operator.setBounds(429, 50, 105, 21);
		
		add(operator);

		client = new JComboBox<String>();
		client.setBounds(122, 78, 105, 21);
		add(client);

		JLabel label_2 = new MyLabel("客户：");
		label_2.setBounds(47, 81, 54, 15);
		add(label_2);
		
		JLabel label_3 = new MyLabel("仓库：");
		label_3.setBounds(370, 78, 54, 15);
		add(label_3);
		
		stock = new JTextField();
		stock.setBounds(429, 78, 105, 21);
		add(stock);
		stock.setEditable(editable);
		stock.setColumns(10);
		
		JLabel label_5 = new MyLabel("备注：");
		label_5.setBounds(47, 387, 75, 15);
		add(label_5);
		
		备注 = new JTextField();
		备注.setBounds(111, 384, 368, 21);
		add(备注);
		备注.setColumns(10);
		备注.setEditable(editable);
		
		JLabel label_6 = new MyLabel("商品列表：");
		label_6.setBounds(47, 113, 86, 15);
		add(label_6);
		
		JLabel lblNewLabel = new MyLabel("折让前总额：");
		lblNewLabel.setBounds(47, 356, 86, 15);
		add(lblNewLabel);
		
		折让前总额 = new JTextField();
		折让前总额.setEditable(false);
		折让前总额.setBounds(125, 353, 66, 21);
		add(折让前总额);
		折让前总额.setColumns(10);
		
		JLabel label_7 = new MyLabel("折让");
		label_7.setForeground(Color.RED);
		label_7.setBounds(201, 356, 54, 15);
		add(label_7);
		
		折让 = new JTextField();
		折让.setBounds(231, 353, 66, 21);
		add(折让);
		折让.setEditable(editable);
		if(type==销售单据类型.销售退货单){
			折让.setEditable(false);
		}
		折让.setColumns(10);
		
		JLabel label_8 = new MyLabel("代金券");
		label_8.setForeground(Color.RED);
		label_8.setBounds(307, 356, 66, 15);
		add(label_8);
		
		代金券金额 = new JTextField();
		代金券金额.setBounds(351, 353, 66, 21);
		add(代金券金额);
		代金券金额.setColumns(10);
		代金券金额.setEditable(editable);
		if(type==销售单据类型.销售退货单){
			代金券金额.setEditable(false);
		}
		
		JLabel label_9 = new MyLabel("折让后总额：");
		label_9.setBounds(426, 356, 85, 15);
		add(label_9);
		
		折让后总额 = new JTextField();
		折让后总额.setEditable(false);
		折让后总额.setBounds(507, 353, 75, 21);
		add(折让后总额);
		折让后总额.setColumns(10);
		
		iniClient();
		iniCommodity();
		
		if (isNew) {
			this.vo.set单据编号("");
			this.vo.set业务员(user.getName());
		}
		display();
	}

	void displayTable() {
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "商品", "单价","数量","金额", "备注" });

		for (CommodityListItemVo o : vo.get出货商品清单()) {
			model.addRow(new String[] {
					o.get商品编号() + ":" + o.get商品名称() + "." + o.get商品型号(),tool.LongStringTransformer.LongToString(o.get单价()),Integer.toString(o.get数量()),tool.LongStringTransformer.LongToString(o.get金额()), o.get备注() });
		}
		if (editable) {
			model.addRow(new String[] { "", "", "" });
		}
		table.setModel(model);
		if (editable) {
			JComboBox<String> temp = new JComboBox<String>();
			for (CommodityVo o : commodities) {
				temp.addItem(o.get编号() + ":" + o.getName() + "." + o.get型号());
			}
			table.getColumnModel().getColumn(0)
					.setCellEditor(new DefaultCellEditor(temp));
		}
	}

	void save() {
		List<CommodityListItemVo> items = vo.get出货商品清单();
		items.clear();
		for (int i = 0; i < table.getRowCount(); i++) {
			CommodityListItemVo temp = new CommodityListItemVo();
			temp.set备注((String) table.getValueAt(i, 4));
			if(((String) table.getValueAt(i, 0)).indexOf(":")==-1||((String) table.getValueAt(i, 0)).indexOf(".")==-1){
				continue;
			}
			temp.set商品编号(((String) table.getValueAt(i, 0)).substring(0,((String) table.getValueAt(i, 0)).indexOf(":")));
			if(((String) table.getValueAt(i, 0)).indexOf(":")+1<((String) table.getValueAt(i, 0)).length())
				temp.set商品名称(((String) table.getValueAt(i, 0)).substring(((String) table.getValueAt(i, 0)).indexOf(":")+1,((String) table.getValueAt(i, 0)).indexOf(".")));
			if(((String) table.getValueAt(i, 0)).indexOf(".")+1<((String) table.getValueAt(i, 0)).length())
				temp.set商品型号(((String) table.getValueAt(i, 0)).substring(((String) table.getValueAt(i, 0)).indexOf(".")+1));
			boolean successed1 = false;
			try {
				long tempMoney = tool.LongStringTransformer.StringToLong((String) table
						.getValueAt(i, 1));
				temp.set单价(tempMoney);
				successed1 = true;
			} catch (NumberFormatException e) {
			}
			boolean successed2=false;
			try {
				int tempNumber = Integer.parseInt((String) table
						.getValueAt(i, 2));
				temp.set数量(tempNumber);
				successed2 = true;
			} catch (NumberFormatException e) {
			}
			if (successed1&&successed2) {
				temp.set金额(temp.get单价()*temp.get数量());
				items.add(temp);
			}
		}
		saveNotTable();
	}

	void subLine() {
		int line = table.getSelectedRow();
		if (line == -1 || line >= vo.get出货商品清单().size()) {
			return;
		} else {
			vo.get出货商品清单().remove(line);
			displayTable();
		}
	}

	void addLine() {
		save();
		displayTable();
	}

	void submit() {
		save();
		display();
		if (vo.get出货商品清单().size() == 0) {
			JOptionPane.showMessageDialog(this, "请填写商品列表\n");
			return;
		}

		switch(user.getAuthority()){
		case 普通权限:if(vo.get折让()>100000L){
			JOptionPane.showMessageDialog(this, "对不起，您的最高折让额度为100000\n");
			return;
		}
		case 最高权限:if(vo.get折让()>500000L){
			JOptionPane.showMessageDialog(this, "对不起，您的最高折让额度为500000\n");
			return;
		}
		}
		DocumentBLService bl;
		try {
			bl = BLServiceManager.load销退售单BLService(null);
				vo.setOperator(user.getName());
				vo.setOperation("库存赠送");
				
				if(vo.get仓库().equals("")){
					JOptionPane.showMessageDialog(this, "仓库不能为空\n");
					return;
				}
				vo.set类型(type);
				Vo result;
				if(审批){
					result=bl.approve(vo);
				}else if(红冲&&!editable){
					result=bl.redRush(vo);
				}else if(红冲&&editable){
					result=bl.redRushAndCopy(vo);
				}else{				
					result = bl.add(vo);
				}
				if (result.isSuccessed()) {
					JOptionPane.showMessageDialog(this, "单据提交成功\n");
					vo=new SaleAndReturnDocumentVo();
				} else {
					JOptionPane.showMessageDialog(this,
							"单据提交失败\n" + result.getFailMessage());
				}
			
		} catch (RemoteException | MalformedURLException | SQLException
				| NotBoundException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		display();
	}

	void iniClient() {
		if (isNew) {
			try {
				ClientBLService clientBL = BLServiceManager
						.getClientBLService(null);
				List<ClientVo> clientList = clientBL.getAll().stream().filter(e->{
					if(e.get类型()==o.客户类型.销售商)
						return true;
					else 
						return false;
				}).collect(Collectors.toList());
				DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
				for (ClientVo o : clientList) {
					model.addElement(o.get姓名());
				}
				client.setModel(model);

			} catch (RemoteException | MalformedURLException
					| NotBoundException | SQLException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器\n" + e.getMessage());
				e.printStackTrace();
			}
		} else {
			DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
			model.addElement(vo.get客户());
			client.setModel(model);
			client.setEnabled(false);
		}
	}
	
	void iniCommodity(){
		try {
			CommodityBLService bl=BLServiceManager.getCommodityBLService(null);
			commodities=bl.getAll();
		} catch (RemoteException | MalformedURLException | NotBoundException
				| SQLException e) {
			JOptionPane.showMessageDialog(this,
					"无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		
	}
	
	void saveNotTable(){
		long sumBefore=0;
		for(CommodityListItemVo o:vo.get出货商品清单()){
			sumBefore=sumBefore+o.get金额();
		}
		long zherang=tool.LongStringTransformer.StringToLong(折让.getText());
		long djq=tool.LongStringTransformer.StringToLong(代金券金额.getText());
		long sumAfter=sumBefore-zherang-djq;
		vo.set折让前总额(sumBefore);
		vo.set折让后总额(sumAfter);
		vo.set折让(zherang);
		vo.set使用代金券金额(djq);
		vo.set业务员(user.getName());
		vo.set客户((String) client.getSelectedItem());
		vo.set仓库(stock.getText());
		vo.set备注(备注.getText());
		
	}
	
	void display(){
		displayTable();
		number.setText(vo.get单据编号());
		折让前总额.setText(tool.LongStringTransformer.LongToString(vo.get折让前总额()));
		折让后总额.setText(tool.LongStringTransformer.LongToString(vo.get折让后总额()));
		代金券金额.setText(tool.LongStringTransformer.LongToString(vo.get使用代金券金额()));
		折让.setText(tool.LongStringTransformer.LongToString(vo.get折让()));
		备注.setText(vo.get备注());
		operator.setText(vo.get业务员());
		client.setSelectedItem(vo.get客户());
		stock.setText(vo.get仓库());
		
	}
}
